import 'dart:async';

import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/test_function/refresh_test_terminal_detail_page_event.dart';
import 'package:e_reception_flutter/ui/test_function/sim_info_page.dart';
import 'package:e_reception_flutter/ui/test_function/test_function_view_model.dart';
import 'package:e_reception_flutter/ui/test_function/test_history_page.dart';
import 'package:e_reception_flutter/ui/test_function/test_scan_id_page.dart';
import 'package:e_reception_flutter/ui/test_function/widgets/input_id_dialog.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';

import 'bean/test_detail_response_bean.dart';

class TestTerminalDetailPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "TestTerminalDetailPage";
  final String hsn;
  final String router;

  const TestTerminalDetailPage({Key key, this.hsn, this.router})
      : super(key: key);

  @override
  _TestTerminalDetailPageState createState() => _TestTerminalDetailPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(
      BuildContext context, String hsn, String router) {
    return RouterUtils.routeForFutureResult(
      context,
      TestTerminalDetailPage(
        hsn: hsn,
        router: router,
      ),
      routeName: TestTerminalDetailPage.ROUTER,
    );
  }
}

class _TestTerminalDetailPageState extends BaseState<TestTerminalDetailPage> {
  TestFunctionViewModel _viewModel;
  TestDetailBean _detailBean;
  AttL4gCardBean _cardBean;
  StreamSubscription _detailStreamSubscription;

  @override
  void initState() {
    super.initState();
    _viewModel = new TestFunctionViewModel(this);
    _viewModel.getTestDetail(context, widget?.hsn);
    _detailStreamSubscription = VgEventBus.global
        .on<RefreshTestTerminalDetailPageEvent>()
        ?.listen((event) {
      //详情数据更新了
      _viewModel.getTestDetail(context, widget?.hsn);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _detailStreamSubscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if ((TestHistoryPage.ROUTER == widget?.router ?? "")) {
          RouterUtils.pop(context);
        } else {
          RouterUtils.pushAndPop(context, TestHistoryPage());
        }
        return false;
      },
      child: Scaffold(
        resizeToAvoidBottomPadding: false,
        resizeToAvoidBottomInset: false,
        backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        body: Column(
          children: [
            _toTopBarWidget(),
            Expanded(child: _toPlaceHolderWidget()),
          ],
        ),
      ),
    );
  }

  Widget _toPlaceHolderWidget() {
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            errorOnClick: () => _viewModel.getTestDetail(context, widget?.hsn),
            loadingOnClick: () =>
                _viewModel.getTestDetail(context, widget?.hsn),
            child: child,
          );
        },
        child: _toInfoWidget());
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "终端检测项",
      isShowBack: true,
      backImgColor: Colors.white,
      titleColor: Colors.white,
      backgroundColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
    );
  }

  Widget _toInfoWidget() {
    return ValueListenableBuilder(
      valueListenable: _viewModel.testDetailValueNotifier,
      builder: (BuildContext context,
          TestDetailAndCardInfoBean detailAndCardInfoBean, Widget Child) {
        _detailBean = detailAndCardInfoBean?.outFactoryDetails;
        _cardBean = detailAndCardInfoBean?.attL4gCard;
        return SingleChildScrollView(
          padding: EdgeInsets.zero,
          child: Column(
            children: [
              _toTerminalBasicInfoWidget(),
              SizedBox(
                height: 12,
              ),
              _toTestProcessWidget(),
              SizedBox(
                height: 9,
              ),
              _toBasicInfoSettings(),
              _toCommonHintWidget("硬件检测"),
              _toCameraAngleWidget(),
              _toWLANNetWidget(),
              _toMobileNetWidget(),
              _toCommonHintWidget("系统检测"),
              _toAndroidVersionWidget(),
              _toTTSWidget(),
              _toAutoOnOffWidget(),
              _toCommonHintWidget("软件配置"),
              _toLaunchWidget(),
              _toUpdateVersionWidget(),
              _toScanBindWidget(),
              _toScanLoginWidget(),
              _toPlayFileWidget(),
              _toOpenManagerWidget(),
              Container(
                  height: 10,
                  color:
                      ThemeRepository.getInstance().getBgOrSplitColor_191E31()),
              _toFaceWidget(),
              Container(
                  height: 10,
                  color:
                      ThemeRepository.getInstance().getBgOrSplitColor_191E31()),
              _toTemWidget(),
              Container(
                  height: 10,
                  color:
                      ThemeRepository.getInstance().getBgOrSplitColor_191E31()),
              _toClearUseWidget(),
              Container(
                  height: 30,
                  color:
                      ThemeRepository.getInstance().getBgOrSplitColor_191E31()),
            ],
          ),
        );
      },
    );
  }

  //基本信息
  Widget _toTerminalBasicInfoWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.symmetric(horizontal: 15),
      color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      child: Column(
        children: [
          _toHsnWidget(),
          SizedBox(
            height: 6,
          ),
          Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _toIdWidget(),
                    SizedBox(
                      height: 6,
                    ),
                    _toSimWidget(),
                  ],
                ),
              ),
              SizedBox(
                width: 10,
              ),
              _toScanBindIdWidget(),
            ],
          ),
          SizedBox(
            height: 6,
          ),
          _toUserWidget(),
          SizedBox(
            height: 15,
          ),
        ],
      ),
    );
  }

  Widget _toScanBindIdWidget() {
    return Visibility(
      visible: StringUtils.isEmpty(_detailBean?.sideNumber ?? ""),
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          TestScanIdPage.navigatorPush(context, _detailBean?.hsn, false);
        },
        child: Container(
          alignment: Alignment.center,
          height: 28,
          width: 63,
          decoration: BoxDecoration(
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            borderRadius: BorderRadius.circular(2),
            border: Border.all(color: Color(0x80FFFFFF), width: 1),
          ),
          child: Text(
            "扫码绑定",
            style: TextStyle(
              fontSize: 13,
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }

  //hsn
  Widget _toHsnWidget() {
    return Row(
      children: [
        Container(
          width: 84,
          alignment: Alignment.centerLeft,
          child: Text(
            "屏幕显示编码：",
            style: TextStyle(fontSize: 12, color: Colors.white, height: 1.1),
          ),
        ),
        Expanded(
          child: Text(
            "${_detailBean?.hsn ?? "-"}",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 12,
              color: Colors.white,
              height: 1.22,
            ),
          ),
        ),
      ],
    );
  }

  //id
  Widget _toIdWidget() {
    return Row(
      children: [
        Container(
          width: 84,
          alignment: Alignment.centerLeft,
          child: Text(
            "机身侧面编号：",
            style: TextStyle(fontSize: 12, color: Colors.white, height: 1.1),
          ),
        ),
        _toIdValueWidget(),
      ],
    );
  }

  Widget _toIdValueWidget() {
    if (StringUtils.isNotEmpty(_detailBean?.sideNumber ?? "")) {
      return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          InputIdDialog.navigatorPushDialog(context,
              id: _detailBean?.sideNumber,
              title: "修改机身侧面编号", onConfirm: (value) {
            if (StringUtils.isNotEmpty(value)) {
              _viewModel.updateId(context, _detailBean?.hsn, value);
            }
          });
        },
        child: Container(
          alignment: Alignment.centerLeft,
          child: Row(
            children: [
              Text(
                "${_detailBean?.sideNumber ?? "-"}",
                style:
                    TextStyle(fontSize: 12, color: Colors.white, height: 1.22),
              ),
              SizedBox(
                width: 5,
              ),
              Container(
                margin: EdgeInsets.only(bottom: 2),
                child: Icon(
                  Icons.arrow_forward_ios,
                  size: 10,
                  color: Colors.white,
                ),
              ),
            ],
          ),
        ),
      );
    } else {
      return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {},
          child: Container(
            alignment: Alignment.center,
            width: 40,
            height: 15,
            decoration: BoxDecoration(
              color: ThemeRepository.getInstance().getMinorRedColor_F95355(),
              borderRadius: BorderRadius.circular(7.5),
            ),
            child: Text(
              "未设置",
              style: TextStyle(fontSize: 10, color: Colors.white, height: 1.2),
            ),
          ));
    }
  }

  //sim
  Widget _toSimWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        // SimInfoPage.navigatorPush(
        //   context,
        //   widget?.hsn,
        //   phone: _cardBean?.phone,
        //   operator: _cardBean?.operator,
        //   setMeal: _cardBean?.setMeal,
        //   agent: _cardBean?.agent,
        //   flowSharing: _cardBean?.flowSharing,
        // );
        String title = StringUtils.isEmpty(_cardBean?.phone??"")?"录入4G卡":"修改4G卡";
        InputIdDialog.navigatorPushDialog(context, id:  _cardBean?.iccid, title: title, onConfirm: (value){
          if(StringUtils.isNotEmpty(value)){
            // _viewModel.bindSimCard(context, widget?.hsn, value, StringUtils.isEmpty(_cardBean?.phone??"")?"00":"01");
            //要先传00
            _viewModel.bindSimCard(context, widget?.hsn, value, "00");
          }
        });
      },
      child: Row(
        children: [
          Container(
            width: 84,
            alignment: Alignment.centerLeft,
            child: Text(
              "4G·SIM卡号：",
              style: TextStyle(fontSize: 12, color: Colors.white, height: 1.1),
            ),
          ),
          Container(
            constraints: BoxConstraints(
                maxWidth: 250
            ),
            child: Text(
              _cardBean?.iccid?? "暂无",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(fontSize: 12, color: Colors.white, height: 1.22),
            ),
          ),
          SizedBox(
            width: 5,
          ),
          Container(
            margin: EdgeInsets.only(bottom: 2),
            child: Icon(
              Icons.arrow_forward_ios,
              size: 10,
              color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  //用户信息
  Widget _toUserWidget() {
    return Row(
      children: [
        Container(
          child: Text(
            "${_detailBean?.nick ?? "-"}",
            style:
                TextStyle(fontSize: 10, color: Color(0xFFA2D2FF), height: 1.2),
          ),
        ),
        Text(
          "·",
          style: TextStyle(fontSize: 10, color: Color(0xFFA2D2FF), height: 1.2),
        ),
        Text(
          "${TimeUtil.format((_detailBean?.updatedate ?? 0) * 1000)}",
          style: TextStyle(fontSize: 10, color: Color(0xFFA2D2FF), height: 1.2),
        ),
      ],
    );
  }

  //进度
  Widget _toTestProcessWidget() {
    double width = ScreenUtils.screenW(context) - 30 - 5 - 15 - 53;
    double completeWidth = 0;
    double percent = 0;
    if ((_detailBean?.allcnt ?? 0) > 0) {
      completeWidth = width *
          ((_detailBean?.passcnt ?? 0 * 1.0) / (_detailBean?.allcnt ?? 0));
      percent =
          ((_detailBean?.passcnt ?? 0) * 1.0) / (_detailBean?.allcnt ?? 0);
    }
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 15),
      alignment: Alignment.centerLeft,
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      "检测进度：",
                      style: TextStyle(
                          fontSize: 11,
                          color: ThemeRepository.getInstance()
                              .getTextColor_D0E0F7(),
                          height: 1.2),
                    ),
                    Text(
                      "${_detailBean?.passcnt ?? 0}",
                      style: TextStyle(
                          fontSize: 11, color: Color(0xFF02B7B7), height: 1.2),
                    ),
                    Text(
                      "/",
                      style: TextStyle(
                          fontSize: 11,
                          color: ThemeRepository.getInstance()
                              .getTextColor_D0E0F7(),
                          height: 1.2),
                    ),
                    Text(
                      "${_detailBean?.allcnt ?? 0}",
                      style: TextStyle(
                          fontSize: 11,
                          color: ThemeRepository.getInstance()
                              .getTextColor_D0E0F7(),
                          height: 1.2),
                    ),
                    Spacer(),
                    Visibility(
                      visible: ((_detailBean?.allcnt ?? 0) -
                              (_detailBean?.passcnt ?? 0)) >
                          0,
                      child: Text(
                        "${(_detailBean?.allcnt ?? 0) - (_detailBean?.passcnt ?? 0)}项未通过",
                        style: TextStyle(
                            fontSize: 11,
                            height: 1.2,
                            color: ThemeRepository.getInstance()
                                .getMinorRedColor_F95355()),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 6,
                ),
                ClipRRect(
                  borderRadius: BorderRadius.circular(1),
                  child: Container(
                    height: 4,
                    color: Color(0xFF3A3F50),
                    child: Row(
                      children: [
                        Container(
                          height: 4,
                          width: completeWidth,
                          decoration: BoxDecoration(
                            color: Color(0xFF00C6C4),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          SizedBox(
            width: 15,
          ),
          Text(
            (percent <= 0) ? "0%" : "${(percent ?? 0).toStringAsFixed(2)}%",
            style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.w600,
                color: Color(0xFF04B0B1),
                height: 1.2),
          ),
          SizedBox(
            width: 5,
          )
        ],
      ),
    );
  }

  //基本信息设置
  Widget _toBasicInfoSettings() {
    return _toCommonTestStatusWidget("基本信息设置", _detailBean?.basicInfo, () {});
  }

  //摄像头角度
  Widget _toCameraAngleWidget() {
    return _toCommonTestStatusWidget("摄像头角度", _detailBean?.cameraAngle, () {});
  }

  //WLAN联网
  Widget _toWLANNetWidget() {
    return _toCommonTestStatusWidget("WLAN联网", _detailBean?.wlan, () {});
  }

  //移动数据
  Widget _toMobileNetWidget() {
    return _toCommonTestStatusWidget("移动数据", _detailBean?.mobileData, () {});
  }

  //安卓版本号
  Widget _toAndroidVersionWidget() {
    return _toCommonTestStatusWidget(
        "安卓版本号", _detailBean?.androidVersion, () {});
  }

  //TTS中文语音播报
  Widget _toTTSWidget() {
    return _toCommonTestStatusWidget("TTS中文语音播报", _detailBean?.tts, () {});
  }

  //定时开关机
  Widget _toAutoOnOffWidget() {
    return _toCommonTestStatusWidget("定时开关机", _detailBean?.timeSwitch, () {});
  }

  //主屏幕锁定
  Widget _toLaunchWidget() {
    return _toCommonTestStatusWidget(
        "主屏幕锁定", _detailBean?.homeScreenLock, () {});
  }

  //自动升级
  Widget _toUpdateVersionWidget() {
    return _toCommonTestStatusWidget("自动升级", _detailBean?.autoUpgrade, () {});
  }

  //设备扫码绑定
  Widget _toScanBindWidget() {
    return _toCommonTestStatusWidget("设备（扫码）绑定", _detailBean?.bind, () {});
  }

  //主体扫码登录
  Widget _toScanLoginWidget() {
    return _toCommonTestStatusWidget("主体（扫码）登录", _detailBean?.login, () {});
  }

  //文件播放
  Widget _toPlayFileWidget() {
    return _toCommonTestStatusWidget("文件播放", _detailBean?.filePlay, () {});
  }

  //启用设备管理
  Widget _toOpenManagerWidget() {
    return _toCommonTestStatusWidget(
        "启用设备管理", _detailBean?.openDeviceManage, () {});
  }

  //人脸识别
  Widget _toFaceWidget() {
    return _toCommonSwitchStatusWidget("人脸识别", _detailBean?.face, () {});
  }

  //测温识别
  Widget _toTemWidget() {
    return _toCommonSwitchStatusWidget("测温识别", _detailBean?.temperature, () {});
  }

  //完成检测，清理使用痕迹
  Widget _toClearUseWidget() {
    return _toCommonTestStatusWidget("完成检测，清理使用痕迹", "03", () {});
  }

  Widget _toCommonHintWidget(String title) {
    return Container(
      alignment: Alignment.centerLeft,
      height: 30,
      padding: EdgeInsets.only(left: 15),
      color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      child: StringUtils.isNotEmpty(title)
          ? Text(
              title,
              style: TextStyle(
                fontSize: 11,
                color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
              ),
            )
          : SizedBox(),
    );
  }

  Widget _toCommonTestStatusWidget(
      String title, String status, Function onTap) {
    return Container(
      height: 54,
      margin: EdgeInsets.symmetric(horizontal: 15),
      alignment: Alignment.centerLeft,
      child: Row(
        children: [
          Text(
            title,
            style: TextStyle(
                fontSize: 14,
                height: 1.2,
                color: ThemeRepository.getInstance().getTextColor_D0E0F7()),
          ),
          Spacer(),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              onTap.call();
            },
            child: _getStatusWidget(status),
          )
        ],
      ),
    );
  }

  Widget _getStatusWidget(String status) {
    if ("01" == status) {
      return Container(
        alignment: Alignment.center,
        width: 63,
        height: 28,
        decoration: BoxDecoration(
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          borderRadius: BorderRadius.circular(2),
          border: Border.all(
              color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
              width: 1),
        ),
        child: Text(
          "已完成",
          style: TextStyle(
            fontSize: 13,
            color: Color(0xFF00C6C4),
          ),
        ),
      );
    } else if ("02" == status) {
      return Container(
        alignment: Alignment.center,
        width: 63,
        height: 28,
        decoration: BoxDecoration(
          color: ThemeRepository.getInstance().getMinorRedColor_F95355(),
          borderRadius: BorderRadius.circular(2),
        ),
        child: Text(
          "未通过",
          style: TextStyle(
            fontSize: 13,
            color: Colors.white,
          ),
        ),
      );
    } else if ("00" == status) {
      return Container(
        alignment: Alignment.center,
        width: 63,
        height: 28,
        decoration: BoxDecoration(
          color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          borderRadius: BorderRadius.circular(2),
        ),
        child: Text(
          "检测",
          style: TextStyle(
            fontSize: 13,
            color: Colors.white,
          ),
        ),
      );
    } else if ("03" == status) {
      return Container(
        alignment: Alignment.center,
        width: 63,
        height: 28,
        decoration: BoxDecoration(
          color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          borderRadius: BorderRadius.circular(2),
        ),
        child: Text(
          "清理",
          style: TextStyle(
            fontSize: 13,
            color: Colors.white,
          ),
        ),
      );
    } else {
      return Container(
        alignment: Alignment.center,
        width: 63,
        height: 28,
        decoration: BoxDecoration(
          color: ThemeRepository.getInstance().getMinorRedColor_F95355(),
          borderRadius: BorderRadius.circular(2),
        ),
        child: Text(
          "未通过",
          style: TextStyle(
            fontSize: 13,
            color: Colors.white,
          ),
        ),
      );
    }
  }

  Widget _toCommonSwitchStatusWidget(
      String title, String status, Function onTap) {
    return Container(
      height: 54,
      margin: EdgeInsets.symmetric(horizontal: 15),
      alignment: Alignment.centerLeft,
      child: Row(
        children: [
          Text(
            title,
            style: TextStyle(
                fontSize: 14,
                height: 1.2,
                color: ThemeRepository.getInstance().getTextColor_D0E0F7()),
          ),
          Spacer(),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              onTap.call();
            },
            child: Image.asset(
              ("01" == status)
                  ? "images/icon_open.png"
                  : "images/icon_close.png",
              width: 36,
            ),
          )
        ],
      ),
    );
  }
}
